package com.keiou.drink;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.Environment;
import android.os.Looper;

import com.keiou.drink.util.AppManager;
import com.keiou.drink.util.CToast;
import com.keiou.drink.util.TDevice;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Bob
 * @data 2014-7-23
 * @describe 全局异常
 */
public class AppException implements UncaughtExceptionHandler {

    private UncaughtExceptionHandler mDefaultHandler;
    private static AppException appException;

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            mDefaultHandler.uncaughtException(thread, ex);
        }
    }

    private AppException() {
        this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    public static AppException getAppExceptionHandler() {
        if (appException == null) {
            appException = new AppException();
        }
        return appException;
    }

    /**
     * 自定义异常处理:收集错误信息&发送错误报告
     *
     * @return true:处理了该异常信息;否则返回false
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        final Context context = AppContext.getInstance().getApplicationContext();
        if (context == null) {
            return false;
        }
        //  final String crashReport = getCrashReport(context, ex);
        new Thread() {
            @Override
            public void run() {

                Looper.prepare();
                //saveErrorLog(crashReport);
                //	sendAppCrashReport(context, crashReport);
                CToast.showShort(context, "程序出现异常,即将退出");
                //Sleep (500);


                Looper.loop();
            }
        }.start();

        try {
            Thread.sleep(1000);
            AppManager.getInstance().AppExit(context);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 获取APP崩溃异常报告
     *
     * @return
     */
    private String getCrashReport(Context context, Throwable ex) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String str = formatter.format(curDate);
        PackageInfo pinfo = TDevice.getPackageInfo(context);
        StringBuffer exceptionStr = new StringBuffer();
        exceptionStr.append("Time:" + str);
        exceptionStr.append("Version: " + pinfo.versionName + "(" + pinfo.versionCode + ")\n");
        exceptionStr.append("Android: " + android.os.Build.VERSION.RELEASE + "(" + android.os.Build.MODEL + ")\n");
        exceptionStr.append("Exception: " + ex.getMessage() + "\n");
        StackTraceElement[] elements = ex.getStackTrace();
        for (int i = 0; i < elements.length; i++) {
            exceptionStr.append(elements[i].toString() + "\n\n\n");
        }
        return exceptionStr.toString();
    }

    public void saveErrorLog(String crashReport) {
        String errorlog = "errorlog.txt";
        String savePath = "";
        String logFilePath = "";
        FileWriter fw = null;
        PrintWriter pw = null;
        try {
            // 判断是否挂载了SD卡
            String storageState = Environment.getExternalStorageState();
            if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Log/";
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                logFilePath = savePath + errorlog;
            }
            // 没有挂载SD卡，无法写文件
            if (logFilePath == "") {
                return;
            }
            File logFile = new File(logFilePath);
            if (!logFile.exists()) {
                logFile.createNewFile();
            }
            fw = new FileWriter(logFile, true);
            pw = new PrintWriter(fw);
            pw.append(crashReport);
            pw.flush();
            pw.close();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                }
            }
        }

    }

    public void sendAppCrashReport(Context cont, String crashReport) {

    }

}
